package com.mediocre.api;


import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class UploadTester {

    @Autowired
    private UploadService uploadService;

    @Test
    @SneakyThrows
    public void handleFileUploadTest() {
        Path path = Paths.get("upload.txt");
        /*System.out.println(path.toString());
        System.out.println(path);
        System.out.println(Files.exists(path));
        System.out.println(Files.readAllLines(path));*/
        FileItem fileItem = new DiskFileItemFactory().createItem("file", MediaType.TEXT_PLAIN_VALUE, true, path.toString());

        try (InputStream inputStream = new FileInputStream(path.toFile()); OutputStream outputStream = fileItem.getOutputStream()) {
            IOUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
        log.info(uploadService.handleFileUpload(multipartFile));
    }

}
